#include "MyMessageBox.h"
#include "WelcomeScene.h"

using namespace cocos2d;
using namespace cocos2d::ui;

int MyMessageBox::state = UNKNOWN;


bool MyMessageBox::init(std::string message, std::string title, Node * node,const std::function<void(Ref*)> &callback1, const std::function<void(Ref*)> &callback2)
{
	if (!Layer::init()) {
		return false;
	}
	auto visibleSize = Director::getInstance()->getVisibleSize();
	MyMessageBox::state = UNKNOWN;

	node->setPosition(visibleSize / 2);
	node->setAnchorPoint(Vec2(0.5, 0.5));
	this->addChild(node);

	ok_btn = dynamic_cast<Button*>(node->getChildByName("ok_btn"));
	cancel_btn = dynamic_cast<Button*>(node->getChildByName("cancel_btn"));
	if (ok_btn == nullptr || cancel_btn == nullptr) {
		log("error");
		return false;
	}
	ok_btn->addClickEventListener([this,callback1](Ref* psender) {
		callback1(this->getParent());
		MyMessageBox::state = OK;
		this->removeFromParent();
		
	});
	cancel_btn->addClickEventListener([this,callback2](Ref* psender) {
		callback2(this->getParent());
		MyMessageBox::state = CANCEL;
		this->removeFromParent();
	});
	dynamic_cast<Text*>(node->getChildByName("message_txt"))->setString(message);
	dynamic_cast<Text*>(node->getChildByName("title_txt"))->setText(title);

	return true;
}


bool MyMessageBox::init( Node * node, const std::function<void(Ref*)> &callback1, const std::function<void(Ref*)> &callback2)
{
	if (!Layer::init()) {
		return false;
	}
	if (node == nullptr) {
		log("error");
		return false;
	}
	auto visibleSize = Director::getInstance()->getVisibleSize();
	MyMessageBox::state = UNKNOWN;

	node->setPosition(visibleSize / 2);
	node->setAnchorPoint(Vec2(0.5, 0.5));
	this->addChild(node);

	ok_btn = dynamic_cast<Button*>(node->getChildByName("ok_btn"));
	cancel_btn = dynamic_cast<Button*>(node->getChildByName("cancel_btn"));
	if (ok_btn == nullptr || cancel_btn == nullptr) {
		log("error");
		return false;
	}
	ok_btn->addClickEventListener([this, callback1](Ref* psender) {
		callback1(this->getParent());
		MyMessageBox::state = OK;
		this->removeFromParent();

	});
	cancel_btn->addClickEventListener([this, callback2](Ref* psender) {
		callback2(this->getParent());
		MyMessageBox::state = CANCEL;
		this->removeFromParent();
	});

	return true;
}

MyMessageBox * MyMessageBox::create(std::string message, std::string title, Node * node,const std::function<void(Ref*)> &callback1, const std::function<void(Ref*)> &callback2)
{
	auto _ins = new MyMessageBox();
	_ins->autorelease();
	if (!_ins->init(message, title, node,callback1,callback2)) {
		return nullptr;
	}
	return _ins;
}

MyMessageBox* MyMessageBox::create(Node* node, const std::function<void(Ref*)> &callback1, const std::function<void(Ref*)> &callback2) {
	auto _ins = new MyMessageBox();
	_ins->autorelease();
	if (!_ins->init(node, callback1, callback2)) {
		return nullptr;
	}
	return _ins;
}